<template>
  <div class="order-list">
    <el-table :data="orders" border stripe>
      <el-table-column prop="orderNumber" label="订单编号" width="180"></el-table-column>
      <el-table-column label="商品信息" min-width="300">
        <template #default="scope">
          <div v-for="item in scope.row.items" :key="item.id" class="order-item">
            <div class="product-info">
              <img :src="item.productImage || '/default-product.jpg'" :alt="item.productName" class="product-image">
              <div class="product-details">
                <div class="product-name">{{ item.productName }}</div>
                <div class="product-quantity">数量: {{ item.quantity }}</div>
                <div class="product-price">单价: ¥{{ item.price }}</div>
              </div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="totalPrice" label="订单金额" width="120">
        <template #default="scope">
          <span class="total-price">¥{{ scope.row.totalPrice }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="订单状态" width="100">
        <template #default="scope">
          <el-tag :type="getStatusClass(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="下单时间" width="160">
        <template #default="scope">
          {{ formatDate(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="cancelReason" label="取消原因" width="200" v-if="hasCancelledOrders">
        <template #default="scope">
          <span v-if="scope.row.status === 4 && scope.row.cancelReason" class="cancel-reason">
            {{ scope.row.cancelReason }}
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button size="small" @click="viewDetail(scope.row.id)">详情</el-button>
          <el-button 
            size="small" 
            type="primary" 
            v-if="scope.row.status === 0" 
            @click="payOrder(scope.row.id)"
            :loading="payingOrderId === scope.row.id"
          >
            支付
          </el-button>
          <el-button 
            size="small" 
            type="danger" 
            v-if="scope.row.status === 0" 
            @click="cancelOrder(scope.row.id)"
            :loading="cancellingOrderId === scope.row.id"
          >
            取消
          </el-button>
          <el-button 
            size="small" 
            type="success" 
            v-if="scope.row.status === 2" 
            @click="completeOrder(scope.row.id)"
            :loading="completingOrderId === scope.row.id"
          >
            确认收货
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { ref, computed } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/stores/user';
import request from '@/utils/request';
import { ElMessage, ElMessageBox } from 'element-plus';

export default {
  name: 'OrderList',
  props: {
    orders: {
      type: Array,
      default: () => []
    }
  },
  emits: ['refresh'],
  setup(props, { emit }) {
    const router = useRouter();
    const userStore = useUserStore();
    const payingOrderId = ref(null);
    const cancellingOrderId = ref(null);
    const completingOrderId = ref(null);

    // 计算是否有已取消的订单
    const hasCancelledOrders = computed(() => {
      return props.orders.some(order => order.status === 4);
    });

    const formatDate = (dateString) => {
      if (!dateString) return '';
      const date = new Date(dateString);
      return date.toLocaleString('zh-CN');
    };

    const getStatusText = (status) => {
      const statusMap = {
        0: '待支付',
        1: '已支付',
        2: '已发货',
        3: '已完成',
        4: '已取消'
      };
      return statusMap[status] || status;
    };

    const getStatusClass = (status) => {
      const classMap = {
        0: 'warning',
        1: 'primary',
        2: 'info',
        3: 'success',
        4: 'danger'
      };
      return classMap[status] || '';
    };

    const viewDetail = (orderId) => {
      router.push({
        path: `/orders/${orderId}`,
        query: { userId: userStore.userId, role: userStore.role }
      });
    };

    const payOrder = async (orderId) => {
      try {
        await ElMessageBox.confirm('确定要支付这个订单吗？', '支付确认', {
          confirmButtonText: '确定支付',
          cancelButtonText: '取消',
          type: 'warning'
        });

        payingOrderId.value = orderId;
        const response = await request.post(`/orders/${orderId}/pay`, null, {
          params: { paymentMethod: 0 } // 默认支付宝支付
        });
        
        if (response.code === 200) {
          ElMessage.success('支付成功');
          emit('refresh');
        } else {
          ElMessage.error(response.message || '支付失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('支付失败: ' + (error.response?.data?.message || '网络错误'));
        }
      } finally {
        payingOrderId.value = null;
      }
    };

    const cancelOrder = async (orderId) => {
      try {
        // 显示取消原因输入对话框
        const { value: cancelReason } = await ElMessageBox.prompt(
          '请输入取消订单的原因：',
          '取消订单',
          {
            confirmButtonText: '确定取消',
            cancelButtonText: '取消',
            inputType: 'textarea',
            inputPlaceholder: '请详细说明取消原因...',
            inputValidator: (value) => {
              if (!value || value.trim().length === 0) {
                return '取消原因不能为空';
              }
              if (value.trim().length < 5) {
                return '取消原因至少需要5个字符';
              }
              if (value.trim().length > 200) {
                return '取消原因不能超过200个字符';
              }
              return true;
            },
            inputErrorMessage: '请输入有效的取消原因',
            type: 'warning'
          }
        );

        cancellingOrderId.value = orderId;
        const response = await request.post(`/orders/${orderId}/cancel`, null, {
          params: { 
            userId: userStore.userId, 
            role: userStore.role,
            cancelReason: cancelReason.trim()
          }
        });
        
        if (response.code === 200) {
          ElMessage.success('订单已成功取消');
          emit('refresh');
        } else {
          ElMessage.error(response.message || '取消失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('取消订单错误:', error);
          // 尝试从错误响应中获取详细信息
          let errorMessage = '取消失败';
          if (error.response && error.response.data) {
            errorMessage = error.response.data.message || error.response.data;
          } else if (error.message) {
            errorMessage = error.message;
          }
          ElMessage.error('取消失败: ' + errorMessage);
        }
      } finally {
        cancellingOrderId.value = null;
      }
    };

    const completeOrder = async (orderId) => {
      try {
        await ElMessageBox.confirm('确认已收到商品吗？', '确认收货', {
          confirmButtonText: '确认收货',
          cancelButtonText: '取消',
          type: 'info'
        });

        completingOrderId.value = orderId;
        const response = await request.post(`/orders/${orderId}/complete`, null, {
          params: { userId: userStore.userId, role: userStore.role }
        });
        
        if (response.code === 200) {
          ElMessage.success('订单已完成');
          emit('refresh');
        } else {
          ElMessage.error(response.message || '操作失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('操作失败: ' + (error.response?.data?.message || '网络错误'));
        }
      } finally {
        completingOrderId.value = null;
      }
    };

    return {
      payingOrderId,
      cancellingOrderId,
      completingOrderId,
      hasCancelledOrders,
      formatDate,
      getStatusText,
      getStatusClass,
      viewDetail,
      payOrder,
      cancelOrder,
      completeOrder
    };
  }
};
</script>

<style scoped>
.order-list {
  margin: 20px 0;
}

.order-item {
  margin: 10px 0;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #fafafa;
}

.product-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.product-image {
  width: 50px;
  height: 50px;
  object-fit: cover;
  border-radius: 4px;
}

.product-details {
  flex: 1;
}

.product-name {
  font-weight: bold;
  margin-bottom: 5px;
}

.product-quantity,
.product-price {
  font-size: 12px;
  color: #666;
  margin-bottom: 2px;
}

.total-price {
  font-weight: bold;
  color: #e6a23c;
}

.cancel-reason {
  color: #f56c6c;
  font-style: italic;
  font-size: 12px;
  word-break: break-all;
  line-height: 1.3;
}
</style>